package com.leilbase.adminservice.controllers;

import com.leilbase.adminservice.async.AsyncComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;

@RestController
public class AdminDemoController {

    @Autowired
    AsyncComponent asyncComponent;

    @Value("${server.port}")
    String port;

    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String hi() {
        return this.port + ":Hello World";
    }

    @RequestMapping("/ajaxerror")
    public String errorTest() {
        int a = 1 / 0;
        return "OK";
    }

    @RequestMapping("/async")
    public String asyncTest() {
        String res = "OK";
        try {
            long start = System.currentTimeMillis();
            Future<Boolean> t1 = asyncComponent.task1();
            Future<Boolean> t2 = asyncComponent.task2();
            while (!t1.isDone() || !t2.isDone()) {
                if (t1.isDone() && t2.isDone()) break;
            }
            long end = System.currentTimeMillis();
            res = "任务全部完成，共耗时：" + (end -start) + "毫秒";
            System.out.println("任务全部完成，共耗时：" + (end -start) + "毫秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

}
